﻿Imports System.IO
Imports System.Data
Imports System.Data.SqlClient
Imports System.Linq
Imports TNCDAL
Imports TNCBAL
Public Class ucOnePaymentVoucher
    Inherits System.Windows.Forms.UserControl
    Dim mPmV As New MPaymentVoucher
    Dim mf As New MFiles
    Dim uti As New Utilities
    Dim _id_filefee As Integer
    Dim _arrayFileFee As ArrayList
    Dim _price As Double
    Dim _isNew As Boolean = False
    Dim _isEdit As Boolean = False
    Dim _id_file As Integer
    Dim _id_cont As Integer
    Dim totalPrice As Double = 0
    Public Sub New(ByVal id_FileFee As Integer, ByVal price As Double)
        InitializeComponent()
        _id_filefee = id_FileFee
        _price = price
    End Sub
    Public Sub New()

        ' This call is required by the designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.

    End Sub
    Public Sub New(ByVal idfile As Integer, ByVal idcont As Integer)
        InitializeComponent()
        'Lấy tất cả các phí của file 
        _id_file = idfile
        _id_cont = idcont
     
    End Sub
    
    Public Sub New(ByVal arrayFileFee As ArrayList, ByVal price As Double)
        InitializeComponent()
        _arrayFileFee = arrayFileFee
        _price = price
        txtAmount.Text = price
    End Sub
    Private Sub BindingDataToGrid()
        Dim query = mPmV.GetListFee(_id_file)
        grid.DataSource = query
        'Hiện bảng tỉ giá và tự tính giá tiền

        txtTigia.Text = mf.GetRatioCurrency(_id_file)
        For index = 0 To grid.Rows.Count - 1

            If grid.Rows(index).Cells("cellCurrency").Value.ToString.Trim() <> "VND" Then
                totalPrice += CDbl(txtTigia.Text) * CDbl(grid.Rows(index).Cells("CellPrice").Value())
            Else
                totalPrice += CDbl(grid.Rows(index).Cells("CellPrice").Value())

            End If

        Next
        txtAmount.Text = totalPrice


    End Sub
    Private Sub FormatGrid()
        grid.Columns("cellPrice").DefaultCellStyle.Format = "#,##0.##"
        grid.Columns("cellPrice").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight

    End Sub

    Private Sub CalculateTotalBuying()
        Dim gridTinhTong As DevComponents.DotNetBar.Controls.DataGridViewX
        gridTinhTong = grid
        'Luôn là giá tiền Việt cần phải đổi theo tỉ giá nằm trong file

        Dim total As Double = 0
        For i As Integer = 0 To gridTinhTong.Rows.Count
            Try

                Dim price As Double

                If CInt(gridTinhTong.Rows(i).Cells(5).Value) = 1 Then
                    'Tiền việt
                    price = Double.Parse(gridTinhTong.Rows(i).Cells(4).Value.ToString)
                    total += price
                Else

                    price = Double.Parse(gridTinhTong.Rows(i).Cells(4).Value.ToString) * CDbl(txtTigia.Text)
                    total += price
                End If

            Catch ex As Exception

            End Try
        Next
        txtAmount.Text = total.ToString("#,##0.##")
    End Sub
    Private Sub LoadImport()
        uti.FillUserCombo(cbDirector)
        datePayment.Value = DateTime.Now()
        'Load thông tin tỉ giá
        txtTigia.Text = mf.GetRatioCurrency(_id_file)
    End Sub
    Private Sub EnableControls(ByVal v As Boolean)

        datePayment.Enabled = v
        txtPMVNo.Enabled = v
        txtCashier.Enabled = v
        txtDescription.Enabled = v
        txtVietBangChu.Enabled = v
        txtReceiver.Enabled = v
        cbDirector.Enabled = v

        btnSave.Enabled = v
        btncancel.Enabled = v
        btnAdd.Enabled = True
        'txtInvoiceNo.Enabled = v
        If _isNew Then
            txtID_PaymentVoucher.Text = 0
            datePayment.Value = DateTime.Now()
            txtPMVNo.Text = ""

            txtCashier.Text = ""
            txtDescription.Text = "Chi Phí File " & mf.getFileNoFile(_id_file)
            ' txtAmount.Text = ""
            ' txtVietBangChu.Text = ""
            txtReceiver.Text = ""
            cbDirector.SelectedIndex = 0
            txtNguoiLapPhieu.Text = GeneralClassBAL._User.FullName
            '  txtInvoiceNo.Text = ""

        End If
        txtPMVNo.Focus()

    End Sub
    Private Sub frmPaymentVoucher_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        LoadImport()
        _isNew = True
        BindingDataToGrid()
        EnableControls(True)
        FormatGrid()
    End Sub

    Private Sub grid_RowEnter(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs)
        'Load vào các textbox
        Dim rw As Integer = e.RowIndex
        Dim dg As DataGridView = CType(sender, DataGridView)
        txtID_PaymentVoucher.Text = dg.Item(0, rw).Value   'row.Item("id").ToString
        txtPMVNo.Text = dg.Item(1, rw).Value
        If dg.Item(4, rw).Value IsNot Nothing Then
            datePayment.Value = CType(dg.Item(4, rw).Value.ToString(), DateTime)
        End If
        txtReceiver.Text = dg.Item(5, rw).Value
        txtAmount.Text = dg.Item(6, rw).Value
        txtDescription.Text = dg.Item(7, rw).Value
        If dg.Item(8, rw).Value IsNot Nothing Then
            cbDirector.SelectedValue = CInt(dg.Item(8, rw).Value)
        End If
        txtCashier.Text = dg.Item(10, rw).Value
        If dg.Item(12, rw).Value IsNot Nothing Then
            txtNguoiLapPhieu.Text = dg.Item(12, rw).Value
        End If
        'If dg.Item(14, rw).Value IsNot Nothing Then
        '    txtInvoiceNo.Text = dg.Item(14, rw).Value
        'End If
    End Sub

    Private Sub grid_DataBindingComplete(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewBindingCompleteEventArgs)
        Dim gridView As DataGridView = CType(sender, DataGridView)

        If gridView IsNot Nothing Then
            For Each r As DataGridViewRow In gridView.Rows
                gridView.Rows(r.Index).HeaderCell.Value = (r.Index + 1).ToString()
            Next

        End If
    End Sub

    Private Sub txtAmount_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtAmount.TextChanged

        If txtAmount.Text <> "" Then
            Dim chuoi As String() = txtAmount.Text.Split(New Char() {","})
            Dim chuoicanchuyen As String = ""
            For Each item As String In chuoi
                chuoicanchuyen += item
            Next
            Dim chuoi1 As String = XuLyChuoi.Doisosangchu(chuoicanchuyen).ToLower().Substring(0, 1)
            Dim chuoi2 As String = XuLyChuoi.Doisosangchu(chuoicanchuyen).ToLower().Substring(1)
            txtVietBangChu.Text = chuoi1.ToUpper() & chuoi2 + "đồng"
            'txtAmount.Text = XuLyChuoi.ThemDauPhayVaoChuoi(chuoicanchuyen)
        End If

        uti.FormatCurr(txtAmount)
    End Sub


    Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
        _isNew = True
        _isEdit = False

        btnEdit.Enabled = False
        btnDelete.Enabled = False
        EnableControls(True)

    End Sub

    Private Sub btnEdit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEdit.Click
        _isEdit = True
        _isNew = False
        EnableControls(True)
        btnAdd.Enabled = False
        btnDelete.Enabled = False
    End Sub

    Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click

        If txtPMVNo.Text = "" Then
            MessageBox.Show("Chưa nhập số Phiếu")
            txtPMVNo.Focus()
            Return
        End If

        If txtReceiver.Text = "" Then
            MessageBox.Show("Chưa nhập tên người nhận")
            txtReceiver.Focus()
            Return
        End If

        If txtAmount.Text = "" Then
            MessageBox.Show("Chưa nhập số tiền")
            txtAmount.Focus()
            Return
        End If

        If txtDescription.Text = "" Then
            MessageBox.Show("Chưa nhập lý do chi")
            txtDescription.Focus()
            Return
        End If



        If _isNew Then
            Dim obj As New tblPaymentVoucher

            'If chkTU.Checked = True Then
            '    obj.ID_AdvanceVoucher = cbAdvanceVoucher.SelectedValue
            'End If

            obj.CreatedDate = datePayment.Value.ToShortDateString
            obj.PaymentVoucherNo = txtPMVNo.Text
            obj.Description = txtDescription.Text
            obj.Reciever = txtReceiver.Text
            obj.Amount = Double.Parse(txtAmount.Text.Replace(".", ""))
            obj.ID_Director = cbDirector.SelectedValue
            obj.Cashier = txtCashier.Text
            obj.ID_User = GeneralClassBAL._User.ID_User
            ' obj.InvoiceNo = txtInvoiceNo.Text
            mPmV.InsertNewRecord(obj)

            'Nếu lúc chọn phiếu chi cho phí thì chạy code này


            'Sau khi thêm xong thì lấy giá trị idPayment mới để thêm vào file feee
            Dim id_PaymentVoucher As Integer = 0
            id_PaymentVoucher = mPmV.getIDNewPaymentVoucher()
            'update vào file fee
            'Duyệt qua bảng chi tiết phí file

            For index = 0 To grid.Rows.Count - 1
                Dim objff As New tblFileFee
                objff.ID_FileFee = CInt(grid.Rows(index).Cells(0).Value)
                objff.ID_PaymentVoucher = id_PaymentVoucher
                Dim mbr As New MBuyingRate
                mbr.UpdatePaymentVoucher(objff)
            Next
        Else
        End If
        datePayment.Enabled = False
        txtPMVNo.Enabled = False
        txtCashier.Enabled = False
        txtDescription.Enabled = False
        txtVietBangChu.Enabled = False
        txtReceiver.Enabled = False
        cbDirector.Enabled = False

        btnSave.Enabled = False
        btncancel.Enabled = False

    End Sub

    Private Sub grid_CellFormatting(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs)


        Dim dg As DataGridView = CType(sender, DataGridView)
        If e.RowIndex >= 0 Then
            If e.RowIndex <= grid.Rows.Count - 1 Then
                Dim c As Color
                If CType(dg.Rows(e.RowIndex).HeaderCell.Value, Integer) Mod 2 <> 0 Then
                    c = Color.BlueViolet
                Else
                    c = Color.White
                End If
                e.CellStyle.BackColor = c
            End If
        End If

    End Sub

    Private Sub btPrint_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        'lấy thông tin của phiếu chi hiện thời
        Dim id As Integer
        Try
            id = Integer.Parse(txtID_PaymentVoucher.Text)
        Catch ex As Exception
            id = 0
        End Try
        Dim pv As tblPaymentVoucher = mPmV.SelectRecordById(id)
        If (pv IsNot Nothing) Then
            Dim rpt As New rptPhieuChi
            'set các giá trị
            If (pv.CreatedDate.HasValue) Then
                Dim chuoiNgay As String = "Ngày " & pv.CreatedDate.Value.Day & " tháng " & pv.CreatedDate.Value.Month & " năm " & pv.CreatedDate.Value.Year
                rpt.SetParameterValue("NgayCT", chuoiNgay)
            Else
                rpt.SetParameterValue("NgayCT", "")
            End If
            rpt.SetParameterValue("SoPhieu", "Số phiếu: " & pv.PaymentVoucherNo)
            rpt.SetParameterValue("NguoiNhan", pv.Reciever)
            rpt.SetParameterValue("LyDo", pv.Description)
            rpt.SetParameterValue("SoTien", pv.Amount.Value.ToString("#,##0.##"))
            rpt.SetParameterValue("BangChu", XuLyChuoi.Doisosangchu(pv.Amount))
            rpt.SetParameterValue("ChungTuKem", "000")
            rpt.SetParameterValue("GiamDoc", pv.tblUser.FullName)
            rpt.SetParameterValue("NguoiLap", txtNguoiLapPhieu.Text)
            'chưa làm
            'rpt.SetParameterValue("NguoiLap", pv.tblUser1.FullName)
            rpt.SetParameterValue("ThuQuy", txtCashier.Text)
            'hien thi
            Dim frm As New FrmReport(rpt)
            frm.ShowDialog()
        Else
            MessageBox.Show("Phiếu để in không hợp lệ!")
        End If
    End Sub

    Private Sub btncancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btncancel.Click
        _isNew = False
        _isEdit = False
        EnableControls(False)
    End Sub
 
End Class